package hsit.design;

import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.FieldDoc;
import com.sun.javadoc.MethodDoc;
import com.sun.javadoc.RootDoc;

/**
 * 获取某一个java文件代码中属性对应的注释
 * 来自：https://blog.csdn.net/Mr1ght/article/details/127508897
 *
 * @author guzt
 * @author huanggy 20230222
 */
public class Doclet {

    private static RootDoc rootDoc;
    private String javaBeanFilePath;

    public static boolean start(RootDoc root) {
        rootDoc = root;
        return true;
    }

    public Doclet(String javaBeanFilePath) {
        this.javaBeanFilePath = javaBeanFilePath;
    }

    public ClassInfo exec() {
        ClassInfo classInfo = new ClassInfo();
        com.sun.tools.javadoc.Main.execute(new String[]{"-doclet", Doclet.class.getName(), "-docletpath",
                Doclet.class.getResource("/").getPath(), "-encoding", "utf-8", javaBeanFilePath});
        ClassDoc[] classes = rootDoc.classes();

        if (classes == null || classes.length == 0) {
            return classInfo;
        }

        ClassDoc classDoc = classes[0];
        // 获取类的信息
        classInfo.setClassName(classDoc.name());
        classInfo.setClassPath(classDoc.toString().replace("."+classDoc.name(), ""));
        classInfo.setClassDesc(classDoc.commentText());
        classInfo.setSuperClassName(classDoc.superclassType() == null ? "" : classDoc.superclassType().typeName());

        // 获取方法的信息
        MethodDoc[] methods = classDoc.methods();
        for (MethodDoc method : methods) {
            ClassMethodInfo methodInfo = new ClassMethodInfo();
            methodInfo.setMethodName(method.name());
            methodInfo.setMethodDesc(method.commentText());
            classInfo.getMethods().add(methodInfo);
        }
        // 获取属性名称和注释
        FieldDoc[] fields = classDoc.fields();
        for (FieldDoc field : fields) {
            ClassFieldInfo fieldInfo = new ClassFieldInfo();
            fieldInfo.setFieldName(field.name());
            fieldInfo.setFieldType(field.type().typeName());
            fieldInfo.setFieldDesc(field.commentText());
            classInfo.getFields().add(fieldInfo);
        }

        return classInfo;
    }
}

